package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.core.ServiceMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Minicat的主类
 */
public class Bootstrap {

    private List<ServiceMapper> serviceMappers = new ArrayList<>();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        for (ServiceMapper sm : serviceMappers) {
            sm.start();
        }
    }




    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.init();
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public void init() {
        try (InputStream in = Bootstrap.class.getResourceAsStream("/server.xml")) {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element rootElement = document.getRootElement();
            List<Node> list = rootElement.selectNodes("//service");
            for (Node serviceNode : list) {
                ServiceMapper sm = new ServiceMapper(serviceNode);
                serviceMappers.add(sm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
